/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.cms.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.sql.DATE;

import org.apache.ibatis.annotations.Param;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.thinkgem.jeesite.common.persistence.JsonResult;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.AppVersion;
import com.thinkgem.jeesite.modules.cms.entity.Record_product;
import com.thinkgem.jeesite.modules.cms.entity.Record_task;
import com.thinkgem.jeesite.modules.cms.service.AppVersionService;
import com.thinkgem.jeesite.modules.cms.service.RecordService_product;
import com.thinkgem.jeesite.modules.cms.service.RecordService_task;

// TODO: Auto-generated Javadoc
/**
 * 文件上传Controller.
 *
 * @author leo
 * @version 2017-02-20
 */
@Controller
@RequestMapping(value = "${adminPath}/FileUpload")
public class FileUploadController extends BaseController {
	
	@Autowired
	private RecordService_task record_taskService;
	@Autowired
	private RecordService_product record_productService;
	@Autowired
	private AppVersionService appVersionService;

	@RequestMapping(value = "upload")
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {

        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);

        return "result";
    }


	
/*
     *采用spring提供的上传文件的方法
     */

    @RequestMapping("springUpload")
    @ResponseBody
    public String  springUpload(HttpServletRequest request,@Value("#{APP_PROP['activiti.export.picture.path']}") String fpath) throws IllegalStateException, IOException
    {
    	String key = "";
    	String keyfield = request.getParameter("keyfield");
    	String productid = request.getParameter("productid");
    	String userid = request.getParameter("userid");
    	String comment = request.getParameter("comment");
    	String picturetype = request.getParameter("picturetype");
    	if(picturetype.length()<=0)
    	{
    		picturetype = "P";
    	}
    	if (keyfield.isEmpty() == false){
    		key = keyfield;
    	}else{
    		key = productid;
    	}
         //long  startTime=System.currentTimeMillis();	
         //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式yyyyMMddHH
        Date d = new Date();
        String datestr = df.format(d);// new Date()为获取当前系统时间
        df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
        String datefilename = df.format(d);
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
        	@SuppressWarnings("unused")
			//String path2 = request.getSession().getServletContext().getRealPath("/springUpload/"+datestr);
        	String path2 = fpath +("/"+datestr);
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                    String path= path2;
                    key = (key==null?"":key).replace("/", ".");
                    String fileName = key+"."+datefilename+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// file.getOriginalFilename();
                    File targetFile = new File(path+"/"+key, fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //上传
                    file.transferTo(targetFile);
                    datestr =targetFile.getPath();
                }
            }
          //long  endTime=System.currentTimeMillis();
            //System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
            Date date = new Date();
            if (keyfield.isEmpty() == false){
            	Record_task record = new Record_task();

        		record.setKeyfield(keyfield);
        		record.setDate(date);
        		record.setTime(date);
        		record.setType(picturetype);
        		record.setUserid(userid);
        		record.setDescription(datestr);
        		record.setDescription2(comment);
        		this.record_taskService.save(record);
        	}else{
        		Record_product record = new Record_product();

        		record.setProductid(productid);
        		record.setDate(date);
        		record.setTime(date);
        		record.setType(picturetype);
        		record.setIsok(1);//1 不合格  0  合格
        		record.setUserid(userid);
        		record.setDescription(datestr);
        		record.setDescription2(comment);
        		this.record_productService.save(record);
        	}
            System.out.println(datestr);
        }else{
        	datestr = "";
        }
        
    	return datestr;  

    }
    
    @RequestMapping("springUpload2")
    @ResponseBody
    public String  springUpload2(HttpServletRequest request,@Value("#{APP_PROP['activiti.export.picture.path']}") String fpath) throws IllegalStateException, IOException
    {
    	String key = "";
    	String keyfield = request.getParameter("keyfield");
    	String productid = request.getParameter("productid");
    	String userid = request.getParameter("userid");
    	String comment = request.getParameter("comment");
    	String picturetype = request.getParameter("picturetype");
    	if(picturetype.length()<=0)
    	{
    		picturetype = "P";
    	}
    	if (keyfield.isEmpty() == false){
    		key = keyfield;
    	}else{
    		key = productid;
    	}
         //long  startTime=System.currentTimeMillis();	
         //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式yyyyMMddHH
        Date d = new Date();
        String datestr = df.format(d);// new Date()为获取当前系统时间
        
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
        	@SuppressWarnings("unused")
			//String path2 = request.getSession().getServletContext().getRealPath("/springUpload/"+datestr);
        	String path2 = fpath +("/"+datestr);
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            List<MultipartFile> iter=multiRequest.getFiles("jpg");
            for (MultipartFile file :iter)
            {
                //一次遍历所有文件
                //MultipartFile file=multiRequest.getFile(iter.toString());
                if(file!=null)
                {
                	d = new Date();
                	df = new SimpleDateFormat("yyyyMMddHHmmssSSS");//设置日期格式
                    String datefilename = df.format(d);
                    String path= path2;
                    key = (key==null?"":key).replace("/", ".");
                    String fileName = key+"."+datefilename+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// file.getOriginalFilename();
                    File targetFile = new File(path+"/"+key, fileName);
                    if(!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    //上传
                    file.transferTo(targetFile);
                    datestr =targetFile.getPath();
                    System.out.println(datestr);
                    
                    Date date = new Date();
                    if (keyfield.isEmpty() == false){
                    	Record_task record = new Record_task();

                		record.setKeyfield(keyfield);
                		record.setDate(date);
                		record.setTime(date);
                		record.setType(picturetype);
                		record.setUserid(userid);
                		record.setDescription(datestr);
                		record.setDescription2(comment);
                		this.record_taskService.save(record);
                	}else{
                		Record_product record = new Record_product();

                		record.setProductid(productid);
                		record.setDate(date);
                		record.setTime(date);
                		record.setType(picturetype);
                		record.setIsok(1);//1 不合格  0  合格
                		record.setUserid(userid);
                		record.setDescription(datestr);
                		record.setDescription2(comment);
                		this.record_productService.save(record);
                	}
                }
                //iter.next();
            }
          //long  endTime=System.currentTimeMillis();
            //System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
            
            
        }else{
        	datestr = "";
        }
        
    	return datestr;  

    }

    //,@Value("#{APP_PROP['app.update.url']}") String appurl
    @RequestMapping("checkAppVer")
    @ResponseBody
    public String checkAppVer(String appcode,String version){
    	String msg = "";//1:url	0:您已是最新版本
    	AppVersion app = appVersionService.getByAppCode(appcode);
    	if (app.getVersion().compareTo(version )> 0 )
    	{
    		msg= "1:"+app.getUrl();
    	}else{
    		msg ="0:您已是最新版本";
    	}
    		
    	return msg;
    }
    
    @RequestMapping("getfiles")
    @ResponseBody
    public JsonResult getfiles(String partnum,String opcode,@Value("#{APP_PROP['activiti.design.picture.path']}") String fpath,@Value("#{APP_PROP['activiti.design.picture.path2']}") String fpath2){
    	JsonResult result = new JsonResult();
		String msg = "";//
		// AppVersion app = appVersionService.getByAppCode(appcode);
		// if (app.getVersion().compareTo(version )> 0 )
		// {
		// msg= "1:"+app.getUrl();
		// }else{
		// msg ="0:您已是最新版本";
		// }
		fpath = String.format("%s/%s/%s", fpath,partnum.substring(0, 11),opcode);
		fpath2 = String.format("%s/%s/%s", fpath2,partnum.substring(0, 11),opcode);
		
		try {
			File file = new File(fpath);
			// 如果这个路径是文件夹
			if (file.isDirectory()) {
				// 获取路径下的所有文件
				File[] files = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					System.out.println("文件：" + files[i].getPath());
					msg = msg +","+ files[i].getPath();
					//msg = msg +","+ fpath2+"/"+files[i].getName();


				}

			} else {

				System.out.println("文件：" + file.getPath());
				result.setRet_code(-1);
				result.setData("目录不存在");
			}
		} catch (Exception e) {
			result.setRet_code(-1);
			result.setData("目录不存在");
		}
		if(msg.length()>1){
			result.setRet_code(0);
			result.setData(msg.substring(1));
		}
		return result;
    }
    
    
    /**
     * 预览pdf文件
     */
    @RequestMapping("getfileByPath")
    @ResponseBody
    public void pdfStreamHandler(String filepath,@Param("request") HttpServletRequest request,@Param("response")HttpServletResponse response) {

        InputStream in = null;
        try {
        	File file = new File(filepath);
            in = new FileInputStream(file);
            // 重置response对象中的缓冲区，该方法可以不写，但是你要保证response缓冲区没有其他数据，否则导出可能会出现问题，
            response.reset();
            response.setContentType("application/octet-stream");
            //直接下载时加attachment,预览时候不加
            response.addHeader("Content-Disposition",
                               "attachment; filename=\"" +file.getName() + "\"");
            response.addHeader("Access-Control-Allow-Origin", "*");
//            response.addHeader("Content-Disposition",
//                               "filename=\"" + GeneralUtil.getFilename(request, file.getFileName()) + "\"");
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                response.getOutputStream().write(buffer, 0, length);
            }
        } catch (Exception e) {
            logger.error("下载文件出错", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    }


	@RequestMapping(value="getfileByPath2", produces="application/octet-stream"+";charset=utf-8")
	@ResponseBody
	public ResponseEntity<byte[]> getMessageImage(String filepath)//@RequestParam(ImageRequestParam) String fileName
			throws IOException {
 
		//String filePath = FinalString.ImagePath + fileName;
		File file = new File(filepath);
 
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("fileName", file.getName());//EncodeingConverter.convertReturnToISO(fileName)
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
 
		ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(FileUtil.readAsByteArray(file), headers,
				HttpStatus.OK);
 
		return result;
 
	}
	@RequestMapping("getfileByPath3")
	@ResponseBody
	public org.springframework.http.ResponseEntity<FileSystemResource> downloadFile(
             @RequestParam("filepath") String   filepath,HttpServletResponse response) {

//log.info("下载文件名称：{}",fileId);
String fileName = null; // 文件名称的编码
InputStream in = null;
OutputStream out = null;
try {
//fileName = new String(fileojb.getfileName.getBytes("Gb2312"), "ISO-8859-1");
//response.setHeader("Content-Disposition", "attachment;fileName=" + fileName); // 设置文件头
File file = new File(filepath);
fileName= file.getName();
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" + fileName);
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return  org.springframework.http.ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));

} catch (Exception e) {
e.printStackTrace();
//log.info("dfsId:{}下载文件失败，cause:{}",fielId,e);
}finally {
}
return null;
}




}